// pages/detail/detail.js
const db = wx.cloud.database(); //初始化数据库
import {
  getTimeNow
} from '../../utils/index'; // 导入自定义 js 功能
//const utils = require('../../utils/util');


Page({

  /**
   * 页面的初始数据
   */
  data: {
    der: '',
    imgs: '',
    datalist: [],
    bottom: '',
    say: '',
    userInfo: '',
    timeago: '',
    nowtime: '',
    says: [],
    _id: '',
    showtext: true,
    saysNumber: 0,
    placeholder: '请输入内容',
    a: '',
    receivePerson: '',
    avinfo: '',
    nameinfo: '',
    wx: '',
    typeName: '',


  },
  // 展开全部评论
  showtext() {
    this.setData({
      showtext: !this.data.showtext
    })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      der: wx.getStorageSync('der'),
    })
    wx.showLoading({
      title: '加载中....',
    })
    // 广告
    // 在页面中定义插屏广告
/*     let interstitialAd = null

    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-909671c7acc8c025'
      })
      interstitialAd.onLoad(() => {})
      interstitialAd.onError((err) => {})
      interstitialAd.onClose(() => {})
    }

    
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })
    } */
    


    const that = this
    db.collection("a").get()
      .then(res => {
        console.log("11111111", res.data[0].a)
        that.setData({
          a: res.data[0].a,
        })
      })
    var user = wx.getStorageSync('key')
    //console.log('头像',wx.getStorageSync('key').avatarUrl)
    if (user) {
      this.setData({
        userInfo: user
      })
    }
    //const that = this
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('acceptDataFromOpenerPage', function (data) {
      /* 设置电话 与 _id 缓存 */
      //wx.setStorageSync('phone', data.data.phonenumber)
      //wx.setStorageSync('_id', data.data._id)

      /*       db.collection('orderReceive').where({
              _openid:   data.data.receivePerson
            }).get({
              success: (res) => {       
                console.log("接单员的wx",res.data[0].wx) 
                that.setData({
                  avinfo: res.data[0].userInfo.avatarUrl,
                  wx: res.data[0].wx,
                  nameinfo: res.data[0].name,
              }) 
           }
        }) */

      that.setData({
        datalist: data,
        //typeName: that.data.datalist.data.name,
        //receivePerson: data.data.receivePerson,
      })
    })


    // 获取接单员的 头像与昵称 , 上传审核时提交的信息
    /*     db.collection('orderReceive').where({
          _openid:  that.data.receivePerson
          
        }).get({
          success: (res) => {       
            console.log("接单员的信息",res.data[0]) 
            this.setData({
              info: res.data[0].userInfo.avatarUrl,
          }) 
       }
    }) */

    // 获取数据库中的评论信息 
    db.collection('order').orderBy("sendtime", "desc").where({
      _id: wx.getStorageSync('_id')
    }).get({
      success: (res) => {
        this.setData({
          says: res.data[0].aaa,

          typeName: that.data.datalist.data.name,


        })
      },
    })

    // 获取数据库中的 ==> 评论条数
    db.collection('order').where({
      _id: wx.getStorageSync('_id')
    }).get({
      success: (res) => {
        this.setData({
          saysNumber: res.data[0].aaa.length,
        })
      }
    })
    wx.hideLoading({})
    //console.log('oppopop', this.data.datalist.data._openid)
  },


  /* 返回顶部 */
  toTop(e) {
    /* console.log(e.detail) */
    wx.pageScrollTo({
      scrollTop: e.detail,
    })
  },

  //点击联系我,并复制出来 公告
  get() {
    wx.showModal({
      confirmColor: '#00FF7F', //确定的颜色
      /*  cancelColor:'#FF4040',  //取消的颜色 */
      showCancel: false,
      title: '点击复制微信号',
      content: '联系我获取-微信：YXHLYF19115314436',
      success(res) {
        if (res.confirm) {
          wx.setClipboardData({
            data: 'YXHLYF19115314436',
            success: function (res) {
              wx.showToast({
                title: '微信号已复制',
                //icon:"none",
                image: "/imgs/提交成功.png", //只能是本地的
                mask: "true" //是否设置点击蒙版，防止点击穿透
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  // 解决：底部input，键盘弹起上移
  // 输入聚焦
  foucus: function (e) {
    var that = this;
    that.setData({
      inputBottom: e.detail.height
    })
  },
  //失去聚焦
  blur: function (e) {
    var that = this;
    that.setData({
      inputBottom: 0
    })
  },

  // 获取评论内容
  getsay(e) {
    this.setData({
      say: e.detail.value,
      // _id:
    })
  },

  // 提交评论内容 入数据库
  send() {
    const that = this.data;
    //判断评论，不能为空
    if (!that.say) {
      wx.showToast({
        icon: 'none',
        title: '评论信息不能为空 ！',
      })
      return;
    }
    // 取出 跳转过来的 详情记录  _id
    const _id = wx.getStorageSync('_id')
    const say = that.say
    if (that.placeholder === '请输入内容') {
      this.setData({
        placeholder: ''
      })
    }
    const placeholder = that.placeholder
    //const imgs =  that.imgs     
    const sendtime = getTimeNow()
    console.log("详情记录_id为", _id)

    wx.cloud.callFunction({
      name: 'getsay',
      data: {
        _id: _id,
        say: placeholder + say,
        sendtime: sendtime,
        //imas: imgs,
        sayavatarUrl: wx.getStorageSync('key').avatarUrl,
        saynickName: wx.getStorageSync('key').nickName
      },
      success: (res) => {
        this.onLoad() // 发送后调用 刷新页面
        this.setData({
          say: '', // 清空输入框的内容
          placeholder: '请输入内容', // 恢复提示
        })
        wx.showToast({
          icon: "none",
          title: '评论成功',
        })
      },
    })

  },

  // 时间 封装的时间方法 ，与数据库中保存的时间 相加减 则可得到 几分钟之前等数据
  diaplayTime: function (dateTimeStamp) {
    let newT = dateTimeStamp.replace(/-/g, '/'); //ios时间格式转换时，要求2019/07/04
    var result;
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var curTime = new Date(newT); //后端返回的是秒数
    var diffValue = now - curTime;
    //console.log('dateTimeStamp',dateTimeStamp);
    //console.log('diffValue',diffValue);
    if (diffValue < 0) {
      return;
    }
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;
    if (monthC >= 1) {
      if (monthC <= 12)
        result = "" + parseInt(monthC) + "月前";
      else {
        result = "" + parseInt(monthC / 12) + "年前";
      }
    } else if (weekC >= 1) {
      result = "" + parseInt(weekC) + "周前";
    } else if (dayC >= 1) {
      result = "" + parseInt(dayC) + "天前";
    } else if (hourC >= 1) {
      result = "" + parseInt(hourC) + "小时前";
    } else if (minC >= 1) {
      result = "" + parseInt(minC) + "分钟前";
    } else {
      result = "刚刚";
    }
    return result;
  },

  //页面刷新
  onShow() {
    this.onLoad()

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.onLoad()

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onLoad()
  },

  // 获取 数据库的评论信息
  /*     getsays() {
        db.collection('order').doc(wx.getStorageSync('_id')).orderBy("createTime","desc").where({
          _id: wx.getStorageSync('_id')
        }).get({
        success: (res) => {       
          console.log("res111为",res.data[0].aaa) 
          this.setData({
            says: res.data[0].aaa,
          }) 
        }
      }) 
    }, */


  //回复评论
  replytext(e) {
    //console.log("评论的e为",e)
    //console.log(e.currentTarget.dataset.id)
    //console.log(e.currentTarget.dataset.name)

    const id = e.currentTarget.dataset.id; //点击评论的 id
    const name = e.currentTarget.dataset.name; //点击评论的 name

    this.setData({
      placeholder: '回复' + name + '：',
    })

  },
  //分享 
  shareto() {
    wx.showToast({
      icon: "none",
      title: '该页面暂不支持分享',
    })
  },

  // 上传图片
  upimgs() {
    let that = this
    wx.showActionSheet({
      itemList: ['上传图片'],
      success(res) {
        console.log(res.tapIndex)
        if (res.tapIndex == 0) {
          wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res) {
              wx.showLoading({
                title: '上传中...',
              })
              let time = Date.now()
              for (var i = 0; i <= res.tempFilePaths.length; i++) {
                wx.cloud.uploadFile({
                    cloudPath: "orderimg/" + time + i,
                    filePath: res.tempFilePaths[i]
                  })
                  .then(res => {
                    that.setData({
                      //imgs: that.data.imgs.concat(res.fileID)
                      imgs: res.fileID
                    })
                    //const that = this.data;
                    const _id = wx.getStorageSync('_id')
                    const imgs = that.data.imgs
                    const sendtime = getTimeNow()
                    wx.cloud.callFunction({
                      name: 'getsayimg',
                      data: {
                        _id: _id,
                        fileType: 'images',
                        sendtime: sendtime,
                        imgs: imgs,
                        sayavatarUrl: wx.getStorageSync('key').avatarUrl,
                        saynickName: wx.getStorageSync('key').nickName
                      },
                      success: (res) => {
                        console.log('图片为：', res)
                        that.onLoad()
                      },
                    })
                    wx.hideLoading()
                    wx.showToast({
                      icon: "none",
                      title: '上传成功',
                    })
                  })
              }
            }
          })
        }
      }
    })
  },

  // 点击预览 图片/取件码
  look(e) {
    //console.log(e)
    console.log('点击的取件码为：', e.currentTarget.dataset.src)
    wx.previewImage({
      //current: e.currentTarget.dataset.src,
      urls: [e.currentTarget.dataset.src],
    })
  },

  // 提醒用户发送取件码
  qjm() {
    const openID = this.data.datalist.data._openid
    const OrderID = this.data.datalist.data.orderid
    const Qujian = this.data.datalist.data.qujian
    const Address = this.data.datalist.data.Businessaddress
    wx.showModal({
          confirmColor: '#B452CD',  
          cancelColor: '#9C9C9C',  
          showCancel: true,
          title: '提醒',
          content: '消息只会推送一次，已推送后不会再推送消息提醒用户，你确定现在提醒用户上传取件码吗？(取件码有时效性 10分钟)',
          success(e) {
 if (e.confirm) {
    // 调用云函数 推送订单被接信息 给用户
    wx.cloud.callFunction({
      name: "sendQJM",
      data: {
        openid: openID,
        orderID: OrderID,
        qujian: Qujian,
        address: Address,
      },
    }).then(res => {
      console.log('推送消息发送成功：', res)
      this.setData({
        typeName: '',
      })
      wx.showToast({
        title: '已推送',
        icon: "none"
      })
      /*           wx.showModal({
                  confirmColor: '#B452CD', //确定的颜色
                  cancelColor: '#9C9C9C', //取消的颜色 
                  showCancel: true,
                  title: '公告',
                  content: '消息已成功推送，请等待片刻。如长时间无回应，可直接联系用户^_^',
                  success(res) {

                  }
                }) */
    }).catch(error => {
      console.log('推送消息发送失败：', error)
    })


 }
          }
        })  



  }




})